﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Globalization;
using System.Text;

namespace CID.Web.Support
{
    public static class JQueryExtensions
    {
        private static readonly Dictionary<string, string> NetToJQueryDatePartFormattersConvertions = new Dictionary<string, string>();

        static JQueryExtensions()
        {
            NetToJQueryDatePartFormattersConvertions.Add("d", "d");
            NetToJQueryDatePartFormattersConvertions.Add("dd", "dd");
            NetToJQueryDatePartFormattersConvertions.Add("ddd", "D");
            NetToJQueryDatePartFormattersConvertions.Add("dddd", "DD");
            NetToJQueryDatePartFormattersConvertions.Add("M", "m");
            NetToJQueryDatePartFormattersConvertions.Add("MM", "mm");
            NetToJQueryDatePartFormattersConvertions.Add("MMM", "M");
            NetToJQueryDatePartFormattersConvertions.Add("MMMM", "MM");
            NetToJQueryDatePartFormattersConvertions.Add("y", "y");
            NetToJQueryDatePartFormattersConvertions.Add("yy", "y");
            NetToJQueryDatePartFormattersConvertions.Add("yyy", "yy");
            NetToJQueryDatePartFormattersConvertions.Add("yyyy", "yy");
        }

        public static IHtmlString GetCurrentDateFormat(this HtmlHelper html)
        {
            var separator = CultureInfo.CurrentUICulture.DateTimeFormat.DateSeparator[0];
            var datePartFormatters = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern.Split(separator);
            var sb = new StringBuilder();
            foreach (var datePartFormatter in datePartFormatters)
            {
                if (NetToJQueryDatePartFormattersConvertions.ContainsKey(datePartFormatter))
                {
                    sb.Append(NetToJQueryDatePartFormattersConvertions[datePartFormatter]);
                    sb.Append(separator);
                }
            }
            sb.Remove(sb.Length - 1, 1);

            return html.Raw(sb.ToString());
        }

        public static IHtmlString GetCurrentDecimalSeparator(this HtmlHelper html)
        {
            return html.Raw(CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator);
        }
    }
}